package com.digua.base.util

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.SystemClock
import androidx.annotation.DrawableRes
import androidx.core.app.NotificationCompat
import com.blankj.utilcode.util.ServiceUtils
import com.blankj.utilcode.util.Utils
import com.blankj.utilcode.util.ViewUtils

class ServiceUtil {
    companion object {
        fun startService(context: Context, intent: Intent) {
            try {
                SystemClock.sleep(5)
                if (ServiceUtils.isServiceRunning(intent.component!!.className)) return
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    context.startForegroundService(intent)
                } else {
                    context.startService(intent)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        fun startForeground(service: Service, notificationId: Int, @DrawableRes logoResId: Int) {
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    val CHANNEL_ID = "nined_dmcontrol_service"
                    val CHANNEL_NAME = "nined_dmcontrol_service_name"
                    val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_NONE)
                    (service.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(channel)
                    val notification: Notification = NotificationCompat.Builder(service, CHANNEL_ID).setCategory(Notification.CATEGORY_SERVICE).setSmallIcon(logoResId).setPriority(NotificationCompat.PRIORITY_MIN).build()
                    service.startForeground(notificationId, notification)
                    //关闭掉通知
                    ViewUtils.runOnUiThreadDelayed({ service.stopForeground(true) }, 200)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        fun stopService(service: Class<*>?) {
            try {
                //此延时操作是为了停止服务前先让通知初始化成功
                ViewUtils.runOnUiThreadDelayed({ ServiceUtils.stopService(service!!) }, 300)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        fun stopService(intent: Intent?) {
            stopService(intent, false)
        }

        fun stopService(intent: Intent?, isDelayed: Boolean) {
            if (intent == null) return
            try {
                //此延时操作是为了停止服务前先让通知初始化成功
                ViewUtils.runOnUiThreadDelayed({ Utils.getApp().stopService(intent) }, (if (isDelayed) 1 else 500).toLong())
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}